package com.example.controller;

import cn.hutool.core.io.FileUtil;
import com.example.result.Result;
import com.example.exception.CustomException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
//
//import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//文件相关接口
@RestController
@RequestMapping("files")
@Tag(name="文件相关接口")
public class FileController {
    //获取根路径+文件夹D:\homework\x-项目\gxysXm\springboot\files
    //System.getProperty("user.dir") 获取当前文件的根目录
    private static final String filePath = System.getProperty("user.dir")+"/files/";

    //上传文件
    @PostMapping("upload")
    @Operation(summary = "上传文件",description="接收文件信息、保存在本地的files目录下")
    public Result upload(MultipartFile file){//文件流的形式接收前端发送过来的文件
        String originalFilename=file.getOriginalFilename();//拿到原始名字  xxx.png
        if (!FileUtil.isDirectory(filePath)){//判断是否存在，如果不存在，先创建目录
            FileUtil.mkdir(filePath);//创建
        }
        //加一个唯一的文件名 System.currentTimeMillis()是一个时间戳
        String fileName =  System.currentTimeMillis()+"_"+originalFilename;
        //文件存储的完整的路径
        String realPath = filePath+fileName;
        try {
            FileUtil.writeBytes(file.getBytes(),realPath);//把file写入到realpath
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("500","文件上传失败");
        }
        String url = "http://localhost:8080/files/dowload/"+fileName;
        return Result.success(url);
    }

    //文件下载显示   http://localhost:9090/files/dowload/1732103526260_%E8%81%94%E6%83%B3%E6%88%AA%E5%9B%BE_20240326200324.png
    @GetMapping("/dowload/{fileName}")//文件下载
    @Operation(summary = "文件下载显示",description="文件下载显示")
    public void dowload(@PathVariable String fileName, HttpServletResponse response){
        try {
            //中文名下载乱码处理 附件
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            response.setContentType("application/octet-stream");

            OutputStream os =response.getOutputStream();
            String realPath = filePath+fileName;//完整文件路径
            byte[] bytes = FileUtil.readBytes(realPath);
            //获取到文件的字节数组
            os.write(bytes);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("500","文件下载失败");
        }
    }

    @PostMapping("edit/upload")
    @Operation(summary = "富文本文件上传",description="富文本文件上传")
    public Map<String,Object> wangEditorUpload(MultipartFile file){
        String originalFilename=file.getOriginalFilename();
        if (!FileUtil.isDirectory(filePath)){//判断u是否存在
            FileUtil.mkdir(filePath);//创建
        }
        //唯一的文件名
        String fileName =  System.currentTimeMillis()+"_"+originalFilename;
        //文件存储的完整的路径
        String realPath = filePath+fileName;
        try {
            FileUtil.writeBytes(file.getBytes(),realPath);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("500","文件上传失败");
        }
        String url = "http://localhost:8080/files/dowload/"+fileName;

        Map<String,Object> resMap = new HashMap<>();
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> urlMap = new HashMap<>();
        urlMap.put("url",url);
        list.add(urlMap);
        resMap.put("errno",0);
        resMap.put("data",list);
        return resMap;
    }


}
